<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\WeChatJSSDK;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Admin\SampleInfo;
use QrCode;
use Log;

class SampleInfoController extends Controller
{
    /*不再提醒预警到期*/
    public function notNotice($barCode) {
        $barCode = trim($barCode, ',');
        $barCode = explode(',', $barCode);
        $res = DB::table('a_sample_info')->whereIn('bar_code', $barCode)->update(['notice' => 0]);
        return out($res, '操作成功！', $barCode);
    }

    /*不合格照片，斗臂车照片*/
    public function photoList() {
        $sql = DB::table('a_sample_info as a')->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')->leftJoin('a_contract as c', 'a.contract_id', '=', 'c.id')->where('a.res', '=', 2)->where('a.non_photo', '=', '');
        if(config('constant.app_name') === 'ShanXiShiJiZhongShi') {
            $sql = $sql->where('c.batchNum', '>', '210007');
        }
        $nonlist = $sql->orderBy('a.test_time', 'desc')->select('a.id', 'a.bar_code', 'b.tool_name', 'c.client_name')->get();
        $zunon = [];
        foreach($nonlist as $item) {
            $zunon[substr($item->bar_code, 0, - 3)][] = $item;
        }
        $sql = DB::table('a_sample_info as a')->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')->leftJoin('a_contract as c', 'a.contract_id', '=', 'c.id')->where('b.tool_id', '=', 47)->where('a.photo', '=', '');
        if(config('constant.app_name') === 'ShanXiShiJiZhongShi') {
            $sql = $sql->where('c.batchNum', '>', '210007');
        }
        $doulist = $sql->orderBy('a.test_time', 'desc')->select('a.id', 'a.bar_code', 'c.client_name')->get();
        $zudou = [];
        foreach($doulist as $item) {
            $zudou[substr($item->bar_code, 0, - 3)][] = $item;
        }
        return view('admin.sampleInfo.photoList', compact('zunon', 'zudou'));
    }

    /*不合格照片，斗臂车照片---提交*/
    public function photoListSub(Request $request) {
        if($request->isMethod('POST')) {
            $post_data = $request->only(['photo', 'non_photo']);
            $id = $request->detail_id;
            $res = $this->photoDeal($id, $post_data);
            if(is_string($res)) {
                return out(0, $res);
            }
            $post_data = $res;
            $result = SampleInfo::where('id', $id)->update($post_data);
            return $result > 0 ? 1 : 0;
        }
    }

    private function photoDeal($id, $post_data) {
        $sampleInfo = SampleInfo::find($id);
        $uploadcon = new UploadController();
        $photos = [
            'photo'     => request('photo', ''),   //照片（斗臂车）
            'non_photo' => request('non_photo', ''), //不合格照片
        ];
        foreach($photos as $column => $val) {
            if(isset($post_data[$column]) && trim($post_data[$column]) !== '') {
                $dir = $column === 'non_photo' ? 'sample_info/non' : ($column === 'photo' ? 'sample_info' : '');
                $res = $uploadcon->render('img', [
                    'dir' => $dir, 'file' => $post_data[$column], 'filename' => $sampleInfo['bar_code'], 'text' => $sampleInfo['bar_code'], 'rotate' => 1, 'aspect_ratio' => 3/4 //高宽比
                ]);
                if($res['code'] === 1) {
                    if($sampleInfo[$column] !== '') {
                        DB::table('a_sample_info')->where('bar_code', $sampleInfo['bar_code'])->update([$column => '']);
                    }
                    $post_data[$column] = $res['data']['path'];
                }
                else {
                    return $res['msg'];
                }
            }
        }
        return $post_data;
    }

    /*备注模板列表*/
    public function remarkList(Request $request) {
        $list = DB::table('a_remark_temp')->where('table', 'sample_info')->orderBy('sort', 'desc')->get();
        if(request()->expectsJson()) {
            $data['data'] = $list;
            return response()->json($data);
        }
        $gaiyao_id = $request->input('gaiyao_id');
        return view('admin.sampleInfo.remark.list',compact('gaiyao_id'));
    }

    /*备注模板删除*/
    public function remarkDel() {
        $res = DB::table('a_remark_temp')->where('id', request()->id)->where('table', 'sample_info')->delete();
        return $res;
    }

    /*备注模板添加*/
    public function remarkAdd() {
        $data = request()->only('content');
        request()->validate(['content' => 'required',]);
        $data['table'] = 'sample_info';
        $data['sort'] = time();
        $res = DB::table('a_remark_temp')->insertGetId($data);
        return $res ? '添加成功' : '添加失败';
    }

    /*列表数据*/
    private function listData($para) {
        $sql = DB::table('a_sample_info as a')->leftJoin('a_contract as b', 'b.id', '=', 'a.contract_id')->leftJoin('a_contract_gaiyao as c', 'c.id', '=', 'a.contract_gaiyao_id')->leftJoin('a_tool as d', 'd.id', '=', 'c.tool_id')->leftJoin('a_tool_class as e', 'e.id', '=', 'd.tool_class_id');
        //           $sql = $sql ->where('a.res', '>', 0);
        if($para) {
            if(isset($para['searcho'])) {
                $searcho = $para['searcho'];
                foreach($searcho as $val) {
                    $name = $val['name'];
                    $value = $val['value'];
                    if($value !== '') {
                        if(strpos($name, 'test_time') > - 1) {
                            $pos = substr($name, - 1, 1);
                            if($pos == 0) {
                                $sql = $sql->whereDate('a.test_time', '>=', $value);
                            }
                            if($pos == 1) {
                                $sql = $sql->whereDate('a.test_time', '<=', $value);
                            }
                        }
                        else {
                            $fuhao = substr($val['name'], 1, 1);
                            $table = $fuhao === '_' ? substr($val['name'], 0, 1) : 'a';
                            $column = $fuhao === '_' ? substr($val['name'], 2) : $val['name'];
                            $sql = $sql->where($table.'.'.$column, $value);
                        }
                    }
                }
            }
            $search = isset($para['search']['value']) ? $para['search']['value'] : '';
            $para_col = isset($para['columns']) ? $para['columns'] : [];
            if(strlen($search) > 0) {
                //判断是否有搜索条件
                //以下匿名函数实现的功能，laravel手册中叫参数分组
                //                dd($search,$para_col);
                $sql = $sql->where(function($query) use ($search, $para_col) {
                    foreach($para_col as $val) {
                        if(isset($val['searchable']) && $val['searchable'] == 'true') {
                            if($val['data'] && $val['data'] != null) {
                                $fuhao = substr($val['data'], 1, 1);
                                $table = $fuhao === '_' ? substr($val['data'], 0, 1) : 'a';
                                $column = $fuhao === '_' ? substr($val['data'], 2) : $val['data'];
                                $query->orWhere($table.'.'.$column, 'like', '%'.escape_like_str($search).'%');
                            }
                        }
                    }
                });
            }
        }
        $isSearch = isset($para['is_search']);
        if($isSearch) {
            if($para['is_search'] == 0) {
                $searchdate = date('Y-m-d 00:00:00', strtotime('-6 months'));
                $sql = $sql->whereDate('a.ctime', '>', $searchdate);
            }
        }

        $count = $sql->count();
        $sql = $sql->leftJoin('a_item_data as f', function($join) {
            $join->on('f.sample_info_id', '=', 'a.id')->where('f.res', '=', 0);
        })->leftJoin('a_testitem as g', 'g.id', '=', 'f.item_id')->leftJoin('a_status_time as h', 'h.contract_id', '=', 'a.contract_id')->leftJoin('a_std_tool_rel as i', function($join) {
            $join->on('i.tool_id', '=', 'c.tool_id')->on('i.std_id', '=', 'c.std_id');
        });
        $sql = $sql->select('a.*', 'b.entrusted_company as b_entrusted_company', 'b.batchNum as b_batchNum', 'b.client_contact as b_client_contact', 'b.client_tel as b_client_tel', 'b.deadline as b_deadline', 'c.voltage as c_voltage', 'c.class as c_class', 'c.unit as c_unit', 'c.std_num as c_std_num', 'c.item_names as c_item_names', 'c.tool_name as c_tool_name', 'c.tool_id as c_tool_id', 'c.item_ids as c_item_ids', 'c.std_id as c_std_id', 'e.name as e_name', 'g.name as g_name', 'h.key as h_key', 'b.paid_status as b_paid_status', 'b.paid_at as b_paid_at', 'b.money as b_money', 'b.paid_num as b_paid_num', 'i.cycle as i_cycle', 'h.approve_end as h_approve_end', 'h.sendback_end as h_sendback_end', 'c.remark as c_remark');
        if(!$isSearch) {
            $perpagecount = request()->query('length', 25);
            $offset = request()->query('start', 0);
            $sql = $sql->offset($offset)->limit($perpagecount);
        }
        $order = isset($para['order']) ? $para['order'] : '';
        if($order) {
            //判断是否启用排序
            foreach($order as $val) {
                $column = $para['columns'][intval($val['column'])]['data'];
                if($column) {
                    $sql = $sql->orderBy($column, $val['dir']);
                }
            }
        }
        $sql = $sql->orderBy('a.ctime', 'desc');
        $sqldata = $sql->get();
        $dealdata = [];
        foreach($sqldata as $value) {
            $barcode = $value->bar_code;
            if(isset($dealdata[$barcode])) {
                $dealdata[$barcode]->g_name .= '，'.$value->g_name;
            }
            else {
                $dealdata[$barcode] = $value;
            }
            $dealdata[$barcode]->g_name = trim($dealdata[$barcode]->g_name, '，');
        }
        $data = [];
        $data['data'] = array_values($dealdata);
        $data['iTotalRecords'] = $data['iTotalDisplayRecords'] = $count;
        return $data;
    }

    /* 试验台账 导出Excel */
    public function exportListShanXiShiJiZhongShi($request, $search) {
        @set_time_limit(0);
        ini_set('max_execution_time', 0);
        ini_set('memory_limit', "-1");
        $para = $request->get('params');
        $para = json_decode($para, true);
        $para['is_search'] = $search;
        $data = $this->listData($para);
        if(is_string($data)) {
            return $data;
        }
        $total = $data['iTotalDisplayRecords'];
        if($total === 0) {
            return '内容为空';
        }
        $data = $data['data'];
        $template_file = './storage/ExcelTemplate/检测台账.xls'; //考虑到兼容Linux，斜杠用“/”
        if(!file_exists($template_file)) {
            return '模板文件不存在';
        }
        $report_num_pre = DB::table('setting')->where('id', '1')->value('report_num_pre');                                                             //报告编号前缀
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_file);                                                                      //读取模板文件
        $worksheet_sam_info = $spreadsheet->getSheet(0);                                                                                               //按索引获取表单，从 0 开始
        $domain = $request->server('HTTP_HOST');                                                                                                       //域名
        $rowIndex_sam_info = 3;                                                                                                                        //样品信息的行号
        $qr_code_path = [];
        foreach($data as $kk => $vv) {
            $worksheet_sam_info->getRowDimension($rowIndex_sam_info)->setRowHeight(75);
            $time = strtotime($vv->ctime);
            $month = date('m', $time);
            $day = date('d', $time);
            $worksheet_sam_info->getCell("A".$rowIndex_sam_info)->setValue($kk + 1);                                                             //序号
            $worksheet_sam_info->getCell("B".$rowIndex_sam_info)->setValue(date('Y', $time));                                                    //年度
            $worksheet_sam_info->getCell("C".$rowIndex_sam_info)->setValue($month.'月第'.ceil($day/7).'周');                                //周次
            $worksheet_sam_info->getCell("D".$rowIndex_sam_info)->setValue($vv->place);                                                          //jia
            $worksheet_sam_info->getCell("E".$rowIndex_sam_info)->setValue($vv->b_entrusted_company);                                            //委托单位
            $worksheet_sam_info->getCell("F".$rowIndex_sam_info)->setValue($vv->b_batchNum);                                                     //批次号
            $worksheet_sam_info->getCell("G".$rowIndex_sam_info)->setValue($vv->bar_code);                                                       //条形码
            $worksheet_sam_info->getCell("H".$rowIndex_sam_info)->setValue($vv->c_voltage);                                                      //额定电压（kV）
            $worksheet_sam_info->getCell("I".$rowIndex_sam_info)->setValue($vv->c_tool_name);                                                    //物资名称
            $worksheet_sam_info->getCell("J".$rowIndex_sam_info)->setValue($vv->e_name);                                                         //物资分类
            $worksheet_sam_info->getCell("K".$rowIndex_sam_info)->setValue($vv->guige_xinghao);                                                  //物资型号
            $worksheet_sam_info->getCell("L".$rowIndex_sam_info)->setValue($vv->c_class);                                                        //分类
            $worksheet_sam_info->getCell("M".$rowIndex_sam_info)->setValue(1);                                                                   //试验数量
            $worksheet_sam_info->getCell("N".$rowIndex_sam_info)->setValue($vv->c_unit);                                                         //计量单位
            $worksheet_sam_info->getCell("O".$rowIndex_sam_info)->setValue($vv->self_num);                                                       //样品自编码
            $worksheet_sam_info->getCell("P".$rowIndex_sam_info)->setValue($vv->production_date);                                                //生产日期
            $worksheet_sam_info->getCell("Q".$rowIndex_sam_info)->setValue($vv->manufacturer);                                                   //生产厂家
            $worksheet_sam_info->getCell("R".$rowIndex_sam_info)->setValue($vv->c_std_num);                                                      //检测标准
            $worksheet_sam_info->getCell("S".$rowIndex_sam_info)->setValue($vv->c_item_names);                                                   //试验项目
            $worksheet_sam_info->getCell("T".$rowIndex_sam_info)->setValue($vv->test_time);                                                      //试验时间
            $worksheet_sam_info->getCell("U".$rowIndex_sam_info)->setValue(($vv->res === 1 ? '合格' : ($vv->res === 0 ? '未检测' : '不合格')));          //检测结果
            $worksheet_sam_info->getCell("V".$rowIndex_sam_info)->setValue($vv->g_name);                                                         //不合格项目
            $worksheet_sam_info->getCell("W".$rowIndex_sam_info)->setValue($vv->next_time);                                                      //有效期
            $worksheet_sam_info->getCell("X".$rowIndex_sam_info)->setValue($report_num_pre.$vv->b_batchNum);                                   //报告编号
            $worksheet_sam_info->getCell("AB".$rowIndex_sam_info)->setValue(($vv->c_tool_id === 47 ? 8000 : 300));                               //检测费用（元）
            $worksheet_sam_info->getCell("AC".$rowIndex_sam_info)->setValue($vv->b_paid_at);                                                     //支付日期
            $worksheet_sam_info->getCell("AD".$rowIndex_sam_info)->setValue(($vv->b_paid_status === 1 ? '已支付' : '未支付'));                         //支付状态
            $worksheet_sam_info->getCell("AE".$rowIndex_sam_info)->setValue($vv->b_paid_num);                                                    //付款合同编号
            $worksheet_sam_info->getCell("AG".$rowIndex_sam_info)->setValue($vv->b_client_contact);                                              //联系人
            $worksheet_sam_info->getCell("AH".$rowIndex_sam_info)->setValue($vv->b_client_tel);                                                  //联系电话

            $rowheight = $worksheet_sam_info->getRowDimension($rowIndex_sam_info)->getRowHeight(); //行高
            /* ---------------- 铭牌照片 -------------------- */
            if(isset($request->export_photo)) {
                $vv->photo = '.'.$vv->photo;
                if(is_file($vv->photo)) {
                    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                    $drawing->setPath($vv->photo);                       //图片的路径
                    $drawing->setResizeProportional(false);              //不保持宽高比
                    $drawing->setWidthAndHeight($rowheight, $rowheight); //高度
                    $drawing->setOffsetX(5);
                    $drawing->setOffsetY(5);
                    $drawing->setCoordinates('Y'.$rowIndex_sam_info); //指定位置,名牌照片
                    $drawing->setWorksheet($worksheet_sam_info);
                }
            }
            /* ---------------- 铭牌照片end -------------------- */
            /* ---------------- 不合格照片 -------------------- */
            if(isset($request->export_nonphoto)) {
                $vv->non_photo = '.'.$vv->non_photo;
                if(is_file($vv->non_photo)) {
                    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                    $drawing->setPath($vv->non_photo); //图片的路径
                    $worksheet_sam_info->getCell("Z".$rowIndex_sam_info);
                    $drawing->setResizeProportional(false);                    //不保持宽高比
                    $drawing->setWidthAndHeight(1.3*$rowheight, $rowheight); //高度
                    $drawing->setOffsetX(5);
                    $drawing->setOffsetY(5);
                    $drawing->setCoordinates('Z'.$rowIndex_sam_info); //指定位置,不合格照片
                    $drawing->setWorksheet($worksheet_sam_info);
                }
            }
            /* ---------------- 不合格照片end -------------------- */

            /* ---------------- 二维码 -------------------- */
            if(isset($request->export_erweima)) {
                $key = $vv->key; //批次的密钥
                $url_name = 'http://'.$domain."/viewRes?id={$vv->id}&k={$key}";
                $qr_code_path[$kk] = "./QrCodeImage/viewResId{$vv->id}Key{$key}.png";
                $qrCode = QrCode::format('png');
                $qrCode = $qrCode->size(120);
                $qrCode = $qrCode->margin(0);
                if($qrCode->generate($url_name, $qr_code_path[$kk])) {
                    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                    $drawing->setPath($qr_code_path[$kk]);               //图片的路径
                    $drawing->setResizeProportional(false);              //不保持宽高比
                    $drawing->setWidthAndHeight($rowheight, $rowheight); //高度
                    $drawing->setOffsetX(5);
                    $drawing->setOffsetY(5);
                    $drawing->setCoordinates('AA'.$rowIndex_sam_info); //指定位置,二维码
                    $drawing->setWorksheet($worksheet_sam_info);
                }
            }
            /* ---------------- 二维码end -------------------- */
            $rowIndex_sam_info ++;
        }
        $styleArray = ['borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,]], 'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, 'wrapText' => TRUE,],];
        $worksheet_sam_info->getStyle('A1:AH'.($rowIndex_sam_info - 1))->applyFromArray($styleArray);
        //----------直接在浏览器下载----start
        $today = date('Y-m-d');
        $outname = '近半年数据，下载时间：'.$today;
        if(isset($para['searcho'])) {
            $parao = array_column($para['searcho'], 'value', 'name');
            $danwei = $parao['b_entrusted_company'] ? '检测单位：'.$parao['b_entrusted_company'].'，' : '';
            $pici = $parao['b_batchNum'] ? '批次号：'.$parao['b_batchNum'].'，' : '';
            $startdate = $parao['test_time_0'];
            $enddate = $parao['test_time_1'];
            $date = '';
            if($startdate || $enddate) {
                $date .= '日期范围：';
                $date .= $enddate ? ($startdate ? $startdate : '').'至'.$enddate : ($startdate ? $startdate.'至'.$today : '');
                $date .= ',';
            }
            $outname = $danwei.$pici.$date.'下载时间：'.$today;
        }

        $file_name = "检测台账(".$outname.").xls";                                   //输出的文件名称
        // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出Excel 07文件
        header('Content-Type: application/vnd.ms-excel');                            //告诉浏览器输出Excel 03版本文件
        header('Content-Disposition: attachment;filename='.urlencode($file_name)); //告诉浏览器输出的文件名称
        header('Cache-Control: max-age=0');                                          //禁止缓存
        //----------直接在浏览器下载----end

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->setPreCalculateFormulas(false); //禁用公式预先计算
        $writer->save('php://output');           //直接在浏览器下载
        //为了防止内存泄露，建议用完手动清理
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        foreach($qr_code_path as $vv) {
            @unlink($vv);
        }
    }

    public function exportList(Request $request, $search) {
        $arr_app_name = ["ShanXiShiJiZhongShi"];
        $app_name = config('constant.app_name');
        if(in_array($app_name, $arr_app_name)) {
            $this->exportListShanXiShiJiZhongShi($request, $search);
            return true;
        }

        set_time_limit(0);
        ini_set('max_execution_time', 0);
        ini_set('memory_limit', - 1);
        $para = $request->get('params');
        $para = json_decode($para, true);
        $para['is_search'] = $search;
        $data = $this->listData($para);
        if(is_string($data)) {
            return $data;
        }
        $total = $data['iTotalDisplayRecords'];
        if($total === 0) {
            return '内容为空';
        }
        $data = $data['data'];
        $template_file = './storage/ExcelTemplate/检测台账.xls'; //考虑到兼容Linux，斜杠用“/”
        if(!file_exists($template_file)) {
            return '模板文件不存在';
        }
        $setting = DB::table('setting')->find('1');
        $report_num_pre = $setting->report_num_pre;                                                                                             //报告编号前缀
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_file);                                                               //读取模板文件
        $worksheet_sam_info = $spreadsheet->getSheet(0);                                                                                        //按索引获取表单，从 0 开始
        //			$domain             = $request->server('HTTP_HOST');  //域名
        $worksheet_sam_info->getCell("A1")->setValue($setting->name_rep.'--样品检测台账');
        $rowIndex_sam_info = 3;  //样品信息的行号
        $qr_code_path = [];
        foreach($data as $kk => $vv) {
            $worksheet_sam_info->getRowDimension($rowIndex_sam_info)->setRowHeight(75);
            $time = strtotime($vv->ctime);
            $month = date('m', $time);
            $day = date('d', $time);
            $worksheet_sam_info->getCell("A".$rowIndex_sam_info)->setValue($kk + 1);                                                        //序号
            $worksheet_sam_info->getCell("B".$rowIndex_sam_info)->setValue($vv->b_entrusted_company);                                       //委托单位
            $worksheet_sam_info->getCell("C".$rowIndex_sam_info)->setValue($report_num_pre.$vv->b_batchNum);                              //报告编号
            $worksheet_sam_info->getCell("D".$rowIndex_sam_info)->setValue(substr($vv->bar_code, - 3, 3).'#');                             //样品号
            $worksheet_sam_info->getCell("E".$rowIndex_sam_info)->setValue($vv->self_num);                                                  //样品自编号
            $worksheet_sam_info->getCell("F".$rowIndex_sam_info)->setValue($vv->c_tool_name);                                               //样品名称
            $worksheet_sam_info->getCell("G".$rowIndex_sam_info)->setValue($vv->guige_xinghao);                                             //规格型号
            $worksheet_sam_info->getCell("H".$rowIndex_sam_info)->setValue($vv->c_voltage);                                                 //额定电压（kV）
            $worksheet_sam_info->getCell("I".$rowIndex_sam_info)->setValue($vv->c_class);                                                   //分类
            $worksheet_sam_info->getCell("J".$rowIndex_sam_info)->setValue(1);                                                              //数量
            $worksheet_sam_info->getCell("K".$rowIndex_sam_info)->setValue($vv->c_unit);                                                    //单位
            $worksheet_sam_info->getCell("L".$rowIndex_sam_info)->setValue($vv->c_item_names);                                              //检测项目
            $worksheet_sam_info->getCell("M".$rowIndex_sam_info)->setValue($vv->c_std_num);                                                 //依据标准
            $worksheet_sam_info->getCell("N".$rowIndex_sam_info)->setValue($vv->test_time);                                                 //试验日期
            $worksheet_sam_info->getCell("O".$rowIndex_sam_info)->setValue($vv->i_cycle.'年');                                             //检测周期
            $worksheet_sam_info->getCell("P".$rowIndex_sam_info)->setValue($vv->next_time);                                                 //有效期
            $worksheet_sam_info->getCell("Q".$rowIndex_sam_info)->setValue(($vv->res === 1 ? '合格' : ($vv->res === 0 ? '未检测' : '不合格')));     //检测结果
            $worksheet_sam_info->getCell("R".$rowIndex_sam_info)->setValue($vv->g_name);                                                    //不合格项目
            $worksheet_sam_info->getCell("T".$rowIndex_sam_info)->setValue(($vv->c_tool_id === 47 ? 8000 : 300));                           //检测费用（元）
            $worksheet_sam_info->getCell("U".$rowIndex_sam_info)->setValue($vv->b_paid_status == 1 ? '已支付' : '未支付');                        //支付状态
            $worksheet_sam_info->getCell("V".$rowIndex_sam_info)->setValue($vv->b_paid_at);                                                 //支付时间
            $worksheet_sam_info->getCell("W".$rowIndex_sam_info)->setValue($vv->b_paid_num);                                                //付款合同编号
            $worksheet_sam_info->getCell("X".$rowIndex_sam_info)->setValue($vv->h_approve_end);                                             //报告批准日期
            $worksheet_sam_info->getCell("Y".$rowIndex_sam_info)->setValue($vv->b_deadline);                                                //要求完成日期
            $worksheet_sam_info->getCell("Z".$rowIndex_sam_info)->setValue($vv->h_sendback_end);                                            //报告发放日期
            $worksheet_sam_info->getCell("AA".$rowIndex_sam_info)->setValue($vv->b_client_contact);                                         //联系人
            $worksheet_sam_info->getCell("AB".$rowIndex_sam_info)->setValue($vv->b_client_tel);                                             //联系电话
            $worksheet_sam_info->getCell("AC".$rowIndex_sam_info)->setValue($vv->c_remark);                                                 //备注

            $rowheight = $worksheet_sam_info->getRowDimension($rowIndex_sam_info)->getRowHeight(); //行高

            /* ---------------- 不合格照片 -------------------- */
            if(isset($request->export_nonphoto)) {
                $vv->non_photo = '.'.$vv->non_photo;
                if(is_file($vv->non_photo)) {
                    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                    $drawing->setPath($vv->non_photo); //图片的路径
                    $worksheet_sam_info->getCell("S".$rowIndex_sam_info);
                    $drawing->setResizeProportional(false);                    //不保持宽高比
                    $drawing->setWidthAndHeight(1.3*$rowheight, $rowheight); //高度
                    $drawing->setOffsetX(5);
                    $drawing->setOffsetY(5);
                    $drawing->setCoordinates('S'.$rowIndex_sam_info); //指定位置,不合格照片
                    $drawing->setWorksheet($worksheet_sam_info);
                }
            }
            /* ---------------- 不合格照片end -------------------- */
            $rowIndex_sam_info ++;
        }
        $styleArray = ['borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,]], 'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, 'wrapText' => TRUE,],];
        $worksheet_sam_info->getStyle('A1:AC'.($rowIndex_sam_info - 1))->applyFromArray($styleArray);
        //----------直接在浏览器下载----start
        $today = date('Y-m-d');
        $outname = '近半年数据，下载时间：'.$today;
        if(isset($para['searcho'])) {
            $parao = array_column($para['searcho'], 'value', 'name');
            $danwei = $parao['b_entrusted_company'] ? '检测单位：'.$parao['b_entrusted_company'].'，' : '';
            $pici = $parao['b_batchNum'] ? '批次号：'.$parao['b_batchNum'].'，' : '';
            $startdate = $parao['test_time_0'];
            $enddate = $parao['test_time_1'];
            $date = '';
            if($startdate || $enddate) {
                $date .= '日期范围：';
                $date .= $enddate ? ($startdate ? $startdate : '').'至'.$enddate : ($startdate ? $startdate.'至'.$today : '');
                $date .= ',';
            }
            $outname = $danwei.$pici.$date.'下载时间：'.$today;
        }

        $file_name = "检测台账(".$outname.").xls";                                   //输出的文件名称
        // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出Excel 07文件
        header('Content-Type: application/vnd.ms-excel');                            //告诉浏览器输出Excel 03版本文件
        header('Content-Disposition: attachment;filename='.urlencode($file_name)); //告诉浏览器输出的文件名称
        header('Cache-Control: max-age=0');                                          //禁止缓存
        //----------直接在浏览器下载----end

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->setPreCalculateFormulas(false); //禁用公式预先计算
        $writer->save('php://output');           //直接在浏览器下载
        //为了防止内存泄露，建议用完手动清理
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        foreach($qr_code_path as $vv) {
            @unlink($vv);
        }
    }


    /* 样品基本信息批量添加 */
    public function add(Request $request) {
        //获取批次的id
        $id = $request->id;
        //获取批次信息
        $batch_info = DB::table('a_contract')->select('batchNum', 'status')->where('id', $id)->first();
        //获取批次状态
        $batch_status = $batch_info->status;
        if($batch_status != 0) {
            return '此批次已提交';
        }

        //获取批次号
        $batch_num = $batch_info->batchNum;
        //获取批次的概要信息
        $data_gaiyao = DB::table('a_contract_gaiyao')->where('contract_id', $id)->get();
        if($data_gaiyao->isEmpty()) {
            return '此批次内容是空的';
        }
        /* foreach ($data_gaiyao as $val) {
            $count = $val->count;
            $index = $val->index;
            $srt_item = $val->item_ids;
            $arr_item = explode(",", $srt_item); //字符串 --> 数组

            for ($i = 0; $i < $count; $i++) {
                $str_suf = sprintf('%03d', $index++);
                $bar_code = $batch_num.$str_suf;
                //构建要插入的数据
                $data_insert = [
                    'bar_code' => $bar_code,
                    'contract_id' => $id,
                    'contract_gaiyao_id' => $val->id,
                    'key' => str_random(6) //用六位随机字符串作为密码
                ];
                //插入数据    insertGetId 返回 ID 值
                $insert_id = DB::table('a_sample_info')->insertGetId($data_insert);

                $data_item = [];
                foreach ($arr_item as $vv) {
                    # code...
                    //构建要插入的数据
                    $data_item[] = [
                        'contract_id' => $id,
                        'contract_gaiyao_id' => $val->id,
                        'sample_info_id' => $insert_id,
                        'item_id' => $vv,
                    ];
                }
                //插入数据    insert 返回true 或 false
                $result = DB::table('a_item_data')->insert($data_item);
            }
        } */

        // if ($result) {
        //改变批次的状态
        $data_status = ['status' => '1'];
        $result3 = DB::table('a_contract')->where('id', $id)->update($data_status);
        // }
        return $result3 ? '1' : '0';
    }

    /* 合同详细信息展示 */
    public function index(Request $request) {
        //获取批次的id
        $id = $request->id;
        //获取批次的详细信息
        $data = DB::table('a_contract_detail')->where('a_contract_id', $id)->get();
        return view('admin.contractDetail.index', compact('data'));
    }

    //写入工器具铭牌信息
    private function upGqjPlate($idsAry,$plates){
        $sampleData = DB::table('a_sample_info as a')
                        ->leftJoin('a_contract_gaiyao as b','a.contract_gaiyao_id','=','b.id')
                        ->whereIn('a.id',$idsAry)->select('a.bar_code_1st','a.bar_code','b.tool_name')->get();
        $changed = false;
        foreach($sampleData as $item){
            $bar_code_1st = $item->bar_code_1st ?: $item->bar_code;
            $doesntExist = DB::table('a_gqj_plate')->where('bar_code_1st',$bar_code_1st)->doesntExist();
            if($plates){
                if($doesntExist){
                    $data = ['bar_code_1st'=>$bar_code_1st,'tool_name'=>$item->tool_name,'plate'=>json_encode(array_values($plates))];
                    $res = DB::table('a_gqj_plate')->insert($data);
                }else{
                    $res = DB::table('a_gqj_plate')->where('bar_code_1st',$bar_code_1st)->update(['plate'=>json_encode(array_values($plates))]);
                }
                $changed = $res ? true : false;
            }
        }
        return $changed;
    }

    /* 样品基本信息展示+信息录入 */
    public function indexInfoLuru(Request $request) {
        if($request->expectsJson()) {
            if($request->isMethod('POST')) {
                $idsAry = explode(',', $request->detail_id);
                //其他操作
                $post_data = $request->only(['self_num', 'guige_xinghao', 'brand', 'manufacturer', 'production_date', 'sample_status', 'photo', 'non_photo', 'batch_num_custom','force_scrap_date','place','third_id']);
                // dd($post_data);
                if($post_data['force_scrap_date'] == '/'){
                    unset($post_data['force_scrap_date']);
                }
                if(count($idsAry) > 1) {
                    $post_data = array_filter($post_data);
                    if($post_data === []) {
                        return 0;
                    }
                }
                else {
                    if(isset($request->gqj_ID) && $request->gqj_ID !== '') {
                        if(strstr($request->gqj_ID_head, '?')) {
                            return out(0, 'ID码错误！');
                        }
                        $gqj_ID_foot = $request->gqj_ID_foot ?: '';
                        $setSys = getCache('setting'); //系统设置（setting_sys）
                        $post_data['gqj_ID'] = $gqjId = $request->gqj_ID_head.$request->gqj_ID.$gqj_ID_foot;
                        if($setSys['gqjID_count'] == 24) {
                            $post_data['gqj_ID'] = $setSys['gqj_com_code'].$setSys['gqj_scode'].$post_data['gqj_ID'].$request->gqjID_check;
                            if($request->gqjID_check != $this->getCheckCode(substr($post_data['gqj_ID'], 0,23))) {
                                return out(0, '校验错误！');
                            }
                        }
                        if($request->is_scan == 0) {     //不是扫描添加
                            $repeat = DB::table('a_sample_info')->where('gqj_ID', $gqjId)->first();
                            if($repeat && $repeat->id != $request->detail_id) {
                                return out(0, 'ID码重复');
                            }
                        }
                        $post_data['pipe_code'] = sprintf('%01d', $request->gqj_ID);
                    }
                    if(isset($request->bar_code_1st)) {
                        $post_data['bar_code_1st'] = $request->bar_code_1st ?: $request->bar_code;
                    }
                }

                if(isset($post_data['photo']) || isset($post_data['non_photo'])) {
                    $sampleInfo = SampleInfo::find($request->detail_id);
                    $uploadcon = new UploadController();
                    if(isset($post_data['photo']) && trim($post_data['photo']) !== '') {
                        $res = $uploadcon->render('img', [
                            'dir' => 'sample_info', 'file' => $post_data['photo'], 'filename' => $sampleInfo['bar_code'], 'text' => $sampleInfo['bar_code'], 'rotate' => 1, 'aspect_ratio' => 3/4  //高宽比
                        ]);
                        if($res['code'] === 1) {
                            if($sampleInfo['photo'] !== '') {
                                DB::table('a_sample_info')->where('bar_code', $sampleInfo['bar_code'])->update(['photo' => '']);
                            }
                            $post_data['photo'] = $res['data']['path'];
                        }
                    }
                    if(isset($post_data['non_photo']) && trim($post_data['non_photo']) !== '') {
                        $res = $uploadcon->render('img', [
                            'dir' => 'sample_info/non', 'file' => $post_data['non_photo'], 'filename' => $sampleInfo['bar_code'], 'text' => $sampleInfo['bar_code'], 'rotate' => 1, 'aspect_ratio' => 3/4 //高宽比
                        ]);
                        if($res['code'] === 1) {
                            if($sampleInfo['non_photo'] !== '') {
                                DB::table('a_sample_info')->where('bar_code', $sampleInfo['bar_code'])->update(['non_photo' => '']);
                            }
                            $post_data['non_photo'] = $res['data']['path'];
                        }
                        else {
                            return out(0, $res['msg']);
                        }
                    }
                }
                $post_data['is_luru'] = 1;
                // dd($post_data);
                $result = SampleInfo::whereIn('id', $idsAry)->update($post_data);
                return $result > 0 ? 1 : 0;
                ;
            }
            else {
                //获取批次的id
                $id = $request->id;
                $data = DB::table('a_sample_info as a')
                    ->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')
                    ->select('a.*', 'b.tool_name', 'b.voltage', 'b.class','b.tool_id')
                    ->where('a.contract_id', $id)
                    ->orderByRaw('a.is_luru asc, a.bar_code asc')->get();

                $result['data'] = $data;
                return response()->json($result);
            }
        }
        else {
            $contract_id = $request->id;
            $contractInfo = DB::table('a_contract')->select('client_name')->find($contract_id);
            $gaiyao = DB::table('a_contract_gaiyao')->where('contract_id', $contract_id)->selectRaw('tool_name,
                    Sum(count) AS count')->groupBy('tool_name')->get();
            $enable_tool_ID = DB::table('setting')->where('id', '1')->value('enable_tool_ID');
            $places = DB::table('setting_sys')->where('key', 'test_place')->value('value');
            $places = $places ? explode(',', $places) : '';
            $signPackage = null;

            try {
                if(config('constant.wechat_app_id')){
                    $WXJSSDK = new WeChatJSSDK();
                    $signPackage = $WXJSSDK->getSignPackage();
                }
            } catch(\Exception $exception) {}
            $factorys = DB::table('a_factory')->orderBy('sort', 'desc')->pluck('name');
            $setSys = getCache('setting'); //系统设置（setting_sys）
            $settingCon = new SettingController();
            if($setSys['gqjID_pro']){
                $gqjID_18_pro = $settingCon->RFID_18($setSys['gqjID_pro']);
            }else{
                $gqjID_18_pro = [
                    'serial'=>0,
                    'sub_count'=>0,
                ];
            }

            return view('admin.sampleInfo.indexInfoLuru', compact('contractInfo', 'enable_tool_ID', 'places', 'signPackage', 'factorys', 'gaiyao', 'setSys', 'gqjID_18_pro'));
        }
    }
    //获取工器具铭牌属性
    private function getToolPlates($gyData){
        $toolNames = [];
        foreach($gyData as $item){
            $toolNames[] = $item->tool_name;
        }
        $toolIds = array_unique($toolNames);
        $plateNames = DB::table('a_tool_plate as a')
            ->leftJoin('a_tool as b','a.tool_id','=','b.id')
            ->whereIn('b.name',$toolNames)
            ->select('a.*','b.name as tool_name')->orderBy('formulas','asc')->get();
        $toolPlates = [];
        foreach($plateNames as $item){
            $toolPlates[$item->tool_name][] = (array)$item;
        }
        return $toolPlates;
    }

    //获取样品铭牌属性
    public function gqjPlate(){
        $sampleId = request('sampleId');
        $sample = DB::table('a_sample_info')->where('id',$sampleId)->first();
        $barcode1st = $sample->bar_code_1st;
        $data['plate'] = DB::table('a_gqj_plate')
            ->where('bar_code_1st',$barcode1st)
            ->first();
        $data['energyStd'] = DB::table('a_energy_std')
            ->where('id',$sample->energy_std_id)
            ->first();
        return response()->json($data);
    }

    /* 样品基本信息展示+结果录入 */
    public function indexResLuru(Request $request) {
        if($request->expectsJson()) {
            if ($request->isMethod('post')) {
                if($request->editDate){
                    $date = $request->date;
                    if ($date) {
                        $sample_ids = $request->input('sample_ids');
                        if(!$sample_ids){
                           return 0;
                        }
                        $count = 0;
                        $samples = DB::table('a_sample_info')->where('contract_id',$request->id)->whereIn('id',$sample_ids)->select('id','test_time','next_time')->get()->keyBy('id');
                        foreach ($samples as $id => $sample) {
                            $seconds = strtotime($date) + strtotime($sample->next_time) - strtotime($sample->test_time);
                            $next_time = date('Y-m-d',$seconds);
                            $upData = ['test_time'=>$date,'next_time'=>$next_time];
                            // dd($id,$upData);
                            $res = DB::table('a_sample_info')->where('id',$id)->update($upData);
                            // dd($seconds,$date,$sample,$next_time);
                            $count += ($res ? 1 : 0);
                        }
                        return $count;
                    }else{
                        return 0;
                    }
                }
            }
            //获取批次的id
            $id = $request->id;
            $manager_id = auth('admin')->user()->id;
            $sql = "SELECT DISTINCT
                        sample_info_id
                    FROM
                        a_item_data
                    WHERE
                        contract_id = {$id} ";
            if(!isAdmin()) {
                $sql .= " AND manager_id = {$manager_id}";
            }

            $sample_info_id = DB::select($sql);
            $arr_sample_info_id = [];
            foreach($sample_info_id as $val) {
                $arr_sample_info_id[] = $val->sample_info_id;
            }
            // dd($arr_sample_info_id);

            $sampleInfo = new SampleInfo();
            $result = $sampleInfo->getTableData2($request->all(), 'contract_gaiyao:id,tool_name,voltage,class', ['bar_code', 'asc'], $arr_sample_info_id);
            // dd($result['data']->toArray());
            if(auth('admin')->user()->role_id === 1) {
                $sample_commit_data = DB::table('a_item_data')->distinct()->select('sample_info_id', 'commit')->where('contract_id', $id)->get();
            }
            else {
                $sample_commit_data = DB::table('a_item_data')->distinct()->select('sample_info_id', 'commit')->where('manager_id', $manager_id)->where('contract_id', $id)->get();
            }
            // dd($sample_commit_data->toArray());

            $res_data = $result['data']->toArray();
            $sample_commit_data = $sample_commit_data->toArray();
            //
            foreach($res_data as $key => $val) {
                foreach($sample_commit_data as $v) {
                    if($val['id'] === $v->sample_info_id) {
                        $res_data[$key]['status'] = $v->commit;
                        break;
                    }
                }
            }
            $result['data'] = $res_data;
            return response()->json($result);
        }
        $contractInfo = DB::table('a_contract')->find($request->id);
        return view('admin.sampleInfo.indexResLuru', compact('contractInfo'));
    }

    //发布提交
    private function upTopicSampleSubmitCount($num) {
        $count = cache('sample_submit_noread_count', 0);
        $count += $num;
        cache()->forever('sample_submit_noread_count', $count);
        $client = new \Mosquitto\Client();
        $client->setCredentials('sample_sub_user', 'sample_sub_user');
        $client->connect("127.0.0.1", 1883, 60);
        $client->onPublish(function() use ($client) {
            $client->disconnect();
        });
        $client->publish('/'.domain().'/sample_info/submit/count', $count);
    }

    /* 样品基本信息展示(条形码打印) */
    public function indexPrintBarCode(Request $request) {
        //获取批次的id
        $id = $request->id;
        //获取批次的客户名称
        $client_name = DB::table('a_contract')->where('id', $id)->value('client_name');
        $setting_info = DB::table('setting_sys')->where('key', 'print_bar_code')->value('value'); //设置信息
        $setting_info = json_decode($setting_info, true);
        if(!isset($setting_info['is_remote_RFID'])) {
            $setting_info['is_remote_RFID'] = "";
        }
        if(!isset($setting_info['remote_ip_RFID'])) {
            $setting_info['remote_ip_RFID'] = "";
        }

        $barCode_JS_file = 'Common'; //前端加载的 打印条形码的 js 文件
        $app_name = config('constant.app_name');
        # 如果项目的条形码格式有个性化需求，就把这个项目的 APP_NAME 放到 $arr_app_name 数组中
        $barCode_JS_file_path = "admin/static/myfolder/js/printBarCodeContent_{$app_name}.js";
        if(file_exists($barCode_JS_file_path)) {
            $barCode_JS_file = $app_name;
        }
        $RFID_JS_file_path = "admin/static/myfolder/js/printRFID{$app_name}.js";
        $RFID_JS_file = '';
        if(file_exists($RFID_JS_file_path)) {
            $RFID_JS_file = $app_name;
        }
        $data = DB::table('a_sample_info as a')->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')->leftJoin('a_tool as c', 'b.tool_id', '=', 'c.id')->leftJoin('a_tool_class as d', 'c.tool_class_id', '=', 'd.id')->where('a.contract_id', $id)->select('a.id', 'a.bar_code', 'a.guige_xinghao', 'a.gqj_ID', 'b.tool_name', 'b.class', 'b.voltage', 'd.name as class_name')->orderBy('a.bar_code', 'asc')->get();
        return view('admin.sampleInfo.indexPrintBarCode', compact('client_name', 'setting_info', 'barCode_JS_file', 'data','RFID_JS_file'));
    }

    /* 生成工器具ID */
    public function generateGqjID(Request $request) {
        // sleep(3);
        if($request->expectsJson()) {
            $id = $request->query('id', 0);
            if($id === 'undefined') {
                return out(1);
            }
            $sql = "SELECT
                        A.id,
                        A.bar_code,
                        A.contract_id,
                        B.tool_name,
                        B.sub_count,
                        B.voltage
                    FROM
                        a_sample_info AS A
                        LEFT JOIN a_contract_gaiyao AS B ON A.contract_gaiyao_id = B.id
                    WHERE
                        A.id = :id";
            $sample_info = DB::select($sql, ['id' => $id]);
            $sample_info = array_shift($sample_info);
            $gqj_ID_8 = DB::table('a_contract')->where('id', $sample_info->contract_id)->value('gqj_ID');
            if(!$gqj_ID_8) {
                $gqj_ID_8 = "????????";
            }

            $voltage_code = DB::table('a_code_vol_map')->where('voltage', $sample_info->voltage)->value('code'); //电压等级码
            if($voltage_code === null) {
                $voltage_code = "??";
            }

            $samplename_code = DB::table('a_code_samplename_map')->where('name', $sample_info->tool_name)->value('code'); //工具类别码
            if($samplename_code === null) {
                $samplename_code = "???";
            }
            $data['head'] = $gqj_ID_8.$voltage_code.$samplename_code;

            $setSys = getCache('setting');
            $settingCon = new SettingController();
            $gqjID_18_pro = $settingCon->RFID_18($setSys['gqjID_pro']);
            #region 数量+序号
            $sub_count = $sample_info->sub_count;
            if($sub_count === 1) {
                # code...
                $index = '1';
            }
            else {
                # code...
                $index = substr($sample_info->bar_code, - 1);
            }
            $data['foot'] = $gqjID_18_pro['sub_count'] ? $sample_info->sub_count.$index : '';
            #endregion  数量+序号
            #region 流水号
            if($index === '1') {
                # 该样品只含一件，或含多件且当前是第一件
                $sql = "SELECT
                            max( pipe_code ) AS pipe_code_max
                        FROM
                            a_sample_info AS A
                            LEFT JOIN a_contract_gaiyao AS B ON A.contract_gaiyao_id = B.id
                            LEFT JOIN a_contract AS C ON A.contract_id = C.id
                        WHERE
                            C.gqj_ID = :gqj_ID
                            AND B.voltage = :voltage
                            AND B.tool_name = :tool_name";

                $pipe_code_max = DB::select($sql, ['gqj_ID' => $gqj_ID_8, 'voltage' => $sample_info->voltage, 'tool_name' => $sample_info->tool_name]);
                $pipe_code_max = $pipe_code_max[0];
                $pipe_code_max = $pipe_code_max->pipe_code_max;
                $data['body'] = sprintf('%0'.$gqjID_18_pro['serial'].'d', $pipe_code_max + 1);
            }
            else {
                $first_barcode = substr_replace($sample_info->bar_code, "1", - 1);
                $pipe_code = DB::table('a_sample_info')->where('bar_code', $first_barcode)->value('pipe_code'); //流水码
                $data['body'] = sprintf('%0'.$gqjID_18_pro['serial'].'d', $pipe_code);
                if(!trim($data['body'], '0')) {
                    $data['body'] = sprintf('%?'.$gqjID_18_pro['serial'].'s', $pipe_code);
                }
                // dd($first_barcode);
            }
            #endregion 流水号
            #region 生成工器具ID-最后一位校验码
            $data['gqjID_check'] = $setSys['gqjID_count'] == 24 ? $this->getCheckCode($setSys['gqj_com_code'].$setSys['gqj_scode'].$data['head'].$data['body'].$data['foot']) : '';
            #endregion
            return response()->json($data);
        }
    }

    /* 生成工器具ID-最后一位校验码 */
    public function getCheckCode($bef23) {
        if(strlen($bef23) !== 23 || strstr($bef23, '?')) {
            return '编码错误,校验失败！';
        }
        //校验码
        $he = 0;
        for($i = 0; $i < strlen($bef23); $i ++) {
            $wi = $i%2 === 0 ? 3 : 1;    //加权因子
            $ai = $bef23[$i];
            $he += $wi*$ai;  //将各位数字与 其相对应的加 权值依次相乘 , 并将乘积相加，得 出和数
        }
        //用和数除以模 数 10，得出余数，根 据余数获取相 应的校验码
        $check = (10 - $he%10)%10;
        return $check;
    }

    //单个提交，结果录入后
    public function oneSubmit(Request $request) {
        $id = $request->id; //sample_info 的 id
        $manager_id = auth('admin')->user()->id;

        if(DB::table('a_item_data')->where(['sample_info_id' => $id, 'manager_id' => $manager_id])->whereIn('commit', [- 1, 0])->count() === 0) {
            return '没有可以提交的数据';
        }

        //先判断此样品的 所属主检人 的所有项目 是否都录入结果
        $sql = "SELECT
                    count( 1 ) = 0  AS res_over
                FROM
                    a_item_data
                WHERE
                    sample_info_id = :sample_info_id
                    AND manager_id = :manager_id
                    AND res =2";
        //如果结果全部录入返回1，否则返回0
        $res_over = DB::select($sql, ['sample_info_id' => $id, 'manager_id' => $manager_id]);
        if(!$res_over[0]->res_over) {
            //结果未全部录入，返回'2'
            return '2';
        }

        //更新a_item_data表的 commit 字段
        $res1 = DB::table('a_item_data')->where('sample_info_id', $id)->where('manager_id', $manager_id)->update(['commit' => '1']);
        if($res1) {
            //增加提交次数
            DB::table('a_sample_info')->where('id', $id)->increment('submit_times', 1);
            //初次提交时间
            DB::table('a_sample_info')->where('id', $id)->whereNull('submit_time')->update(['submit_time' => date('Y-m-d H:i:s')]);
        }

        //判断当前样品的所有试验项目是否都提交
        $item_count = DB::table('a_item_data')->where('sample_info_id', $id)->count();
        $commit_count = DB::table('a_item_data')->where('sample_info_id', $id)->where('commit', '1')->count();
        if($item_count === $commit_count) {
            //当前样品的所有项目都已经提交，更新a_sample_info表的 status0 字段
            DB::table('a_sample_info')->where('id', $id)->update(['status0' => '1']);
        }

        // 提交后检查当前批次 未提交的记录数
        $res2 = DB::table('a_item_data')->where('contract_id', $request->batch_id)->where('commit', '0')->count();
        //如果为0，说明本批次已全部提交，此时改变contract的状态
        if($res2 === 0) {
            DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '8']);

            //查询此批次是否记录过试验完成的时间
            $test_end = DB::table('a_status_time')->where('contract_id', $request->batch_id)->value('test_end');
            if(!$test_end) {
                # 如果没记录过，就记录试验完成的时间
                $now_time = date("Y/m/d H:i:s"); //当前时间
                DB::table('a_status_time')->where('contract_id', $request->batch_id)->update(['test_end' => $now_time]);
            }
        }

        if($res1 >= 0 && !config('constant.is_lan')) {
            $this->upTopicSampleSubmitCount(1);
        }
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //批量提交，结果录入后
    public function batchSubmit(Request $request) {
        $arr_ids = $request->checkID; //sample_info 的id ，是个数组
        $manager_id = auth('admin')->user()->id;
        $b = false; //一个样品的结果是否全部录入的标志
        $num=0;
        $sub_num=0;
        foreach($arr_ids as $id) {
            //先判断此样品的 所属主检人 的所有项目 是否都录入结果
            $sql = "SELECT
                        count( 1 ) = 0  AS res_over
                    FROM
                        a_item_data
                    WHERE
                        sample_info_id = :sample_info_id
                        AND manager_id = :manager_id
                        AND res =2";
            //如果结果全部录入返回1，否则返回0
            $res_over = DB::select($sql, ['sample_info_id' => $id, 'manager_id' => $manager_id]);
            if(!$res_over[0]->res_over) {
                //结果未全部录入
                $b = true;
                $num++;
                continue;
            }

            //更新a_item_data表的 commit 字段
            $res1 = DB::table('a_item_data')->where('sample_info_id', $id)->where('manager_id', $manager_id)->update(['commit' => '1']);
            if($res1) {
                $sub_num++;
                //增加提交次数
                DB::table('a_sample_info')->where('id', $id)->increment('submit_times', 1);
                //初次提交时间
                DB::table('a_sample_info')->where('id', $id)->whereNull('submit_time')->update(['submit_time' => date('Y-m-d H:i:s')]);
            }

            //判断当前样品的所有试验项目是否都提交
            $item_count = DB::table('a_item_data')->where('sample_info_id', $id)->count();
            $commit_count = DB::table('a_item_data')->where('sample_info_id', $id)->where('commit', '1')->count();
            if($item_count === $commit_count) {
                //当前样品的所有项目都已经提交，更新a_sample_info表的 status0 字段
                DB::table('a_sample_info')->where('id', $id)->update(['status0' => '1']);
            }

        }

        // 提交后检查当前批次 未提交的记录数
        $res2 = DB::table('a_item_data')->where('contract_id', $request->batch_id)->where('commit', '0')->count();
        //如果为0，说明本批次已全部提交，此时改变contract的状态
        if($res2 === 0) {

            DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '8']);

            //查询此批次是否记录过试验完成的时间
            $test_end = DB::table('a_status_time')->where('contract_id', $request->batch_id)->value('test_end');
            if(!$test_end) {
                # 如果没记录过，就记录试验完成的时间
                $now_time = date("Y/m/d H:i:s"); //当前时间
                DB::table('a_status_time')->where('contract_id', $request->batch_id)->update(['test_end' => $now_time]);
            }
        }

        if($b) {
           return "存在".$num."条结果未全部录入的样品，请检查";
        }
        if(!config('constant.is_lan')){
            $this->upTopicSampleSubmitCount(count($arr_ids));
        }
        return "批量提交成功".$sub_num.'条数据';
    }

    /* 样品基本信息展示（审核） */
    public function indexCheck(Request $request) {
        //获取批次的id
        $id = $request->id;

        if($request->expectsJson()) {
            // ajax提交
            if($request->isMethod('POST')) {
                //
            }
            else {
                $sql = "SELECT DISTINCT
                            `a`.*,
                            `b`.`tool_name`,
                            `b`.`voltage`,
                            `b`.`class`,
                            c.back_count
                        FROM
                            `a_sample_info` AS `a`
                        LEFT JOIN `a_contract_gaiyao` AS `b` ON `a`.`contract_gaiyao_id` = `b`.`id`
                        LEFT JOIN (
                            SELECT
                                sample_info_id,
                                COUNT(1) AS back_count
                            FROM
                                `a_reject_log`
                            GROUP BY
                                sample_info_id
                        ) AS c ON `a`.`id` = `c`.`sample_info_id`
                        WHERE
                            `a`.`contract_id` = {$id}
                        ORDER BY
                            `bar_code` ASC";

                $result['data'] = DB::select($sql);
                return response()->json($result);
            }
        }
        else {
            //非 ajax提交
            $contractInfo = DB::table('a_contract')->select('id', 'client_name')->find($id);

            return view('admin.sampleInfo.indexCheck', compact('contractInfo'));
        }
    }

    /* 样品基本信息展示（查看） */
    public function viewCheck(Request $request) {
        //获取批次的id
        $id = $request->id;

        if($request->expectsJson()) {
            // ajax提交
            if($request->isMethod('POST')) {
                //
            }
            else {
                $sampleInfo = new SampleInfo();
                $result = $sampleInfo->getTableData($request->all(), 'contract_gaiyao:id,tool_name,voltage,class', ['bar_code', 'asc'], [['contract_id', '=', $id]]);
                return response()->json($result);
            }
        }
        else {
            //非 ajax提交
            $contractInfo = DB::table('a_contract')->select('id', 'client_name')->find($id);

            return view('admin.sampleInfo.viewCheck', compact('contractInfo'));
        }
    }

    /* 样品基本信息展示（打印合格证） */
    public function indexPrintPassedCard(Request $request) {
        if($request->expectsJson()) {
            if($request->isMethod('POST')) {
                //
            }
            else {
                //获取批次的id
                $id = $request->id;
                // $contractDetail = new ContractDetail();
                // $result = $contractDetail->getTableData($request->all(), 'manager:id,realname,partner', null, [['a_contract_id', '=', $id]]);
                // return response()->json($result);
                $data = DB::table('a_sample_info')
                        ->leftJoin('a_contract_gaiyao', 'a_contract_gaiyao.id', '=', 'a_sample_info.contract_gaiyao_id')
                        ->leftJoin('a_contract', 'a_contract.id', '=', 'a_sample_info.contract_id')
                        ->leftJoin('a_tool', 'a_tool.id', '=', 'a_contract_gaiyao.tool_id')
                        ->leftJoin('a_tool_class', 'a_tool_class.id', '=', 'a_tool.tool_class_id')
                        ->leftJoin('a_code2_samplename_map', 'a_code2_samplename_map.name', '=', 'a_contract_gaiyao.tool_name')
                        ->where('a_sample_info.contract_id', $id)
                        ->select('a_sample_info.*', 'a_contract_gaiyao.tool_name','a_contract_gaiyao.tool_id', 'a_contract_gaiyao.std_num', 'a_contract_gaiyao.class', 'a_contract_gaiyao.voltage', 'a_contract.name_ABC', 'a_contract.status as contract_status', 'a_contract.created_at', 'a_code2_samplename_map.code', 'a_tool_class.name as class_name')
                        ->orderBy('bar_code', 'asc')->get();
                $jsonData['data'] = $data;

                return response()->json($jsonData);
            }
        }
        else {
            $contractInfo = DB::table('a_contract')->select('client_name')->find($request->id);
            $setting_info = DB::table('setting')->where('id', '1')->first(); //设置信息
            $print_style = DB::table('setting_sys')->where('key', 'print_passedCard_style')->value('value');
            $have_barcode = DB::table('setting_sys')->where('key', 'have_barcode')->value('value');
            $hasAqm = DB::table('a_contract_gaiyao')->where('contract_id', $request->id)->where('tool_id', 1)->exists();    //判断是否有安全帽
            return view('admin.sampleInfo.indexPrintPassedCard', compact('contractInfo', 'setting_info', 'print_style', 'have_barcode', 'hasAqm'));
        }
    }

    /*自定义打印合格证*/
    public function printPass() {
        // dd(111);
        $setting_info = DB::table('setting')->where('id', '1')->first(); //设置信息
        if(auth('admin')->user()->id === 1) {
            $setting_info->passedcard_remote_ip = '127.0.0.1';
        }
        return view('admin.sampleInfo.printPass', compact('setting_info'));
    }

    //单个审核
    public function oneCheck(Request $request) {
        DB::beginTransaction();
        try {
            $id = (int)$request->id; //sample_info 的 id
            //  update 返回受影响的行数
            $auditman = auth()->user()->realname ? auth()->user()->realname : auth()->user()->username;
            $status0 = $request->status;
            //记录驳回原因
            if($status0 == - 1 && $request->reason !== '') {
                $data_reject = ['sample_info_id' => $id, 'contract_id' => intval($request->batch_id), 'content' => trim($request->reason), 'manager_realname' => $auditman];
                DB::table('a_reject_log')->insert($data_reject);
            }
            $updata = ['status0' => $status0, 'audit_man' => $auditman];
            DB::table('a_sample_info')->where('id', $id)->increment('check_times', 1, $updata);
            $res1 = DB::table('a_item_data')->where('sample_info_id', $id)->update(['commit' => $request->status]);

            $contract_id = $request->batch_id;
            //初次审核时间
            $date = date('Y-m-d H:i:s');
            DB::table('a_sample_info')->where('id', $id)->whereNull('check_time')->update(['check_time' => $date]);
            DB::table('a_status_time')->where('contract_id', $contract_id)->whereNull('check_start')->update(['check_start' => $date]);

            // 审核后检查 未审核通过 的记录数
            $res3 = DB::table('a_sample_info')->where('contract_id', $contract_id)->where('status0', ' <> ', '2')->count();
            //如果为0，说明本批次已全部审核通过，此时改变contract的状态
            //0-受理中，1-受理完成，5-试验中，8-试验完成，11-审核完成，13-批准驳回，14-批准完成，17-全部检测工作完成，等待退样，20-退样完成
            if($res3 === 0) {
                DB::table('a_contract')->where('id', $contract_id)->update(['status' => '11']);

                //查询此批次是否记录过审核完成的时间
                $check_end = DB::table('a_status_time')->where('contract_id', $contract_id)->value('check_end');
                if(!$check_end) {
                    # 如果没记录过，就记录审核完成的时间
                    $now_time = date("Y/m/d H:i:s"); //当前时间
                    DB::table('a_status_time')->where('contract_id', $contract_id)->update(['check_end' => $now_time]);
                }
            }
            else {
                DB::table('a_contract')->where('id', $contract_id)->update(['status' => '8']);
            }
            DB::commit();
        } catch(\Exception $exception) {
            DB::rollBack();
            return '0';
        }

        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //批量审核
    public function batchCheck(Request $request) {
        DB::beginTransaction();
        try {
            $ids = $request->checkID;
            $contract_id = $request->batch_id;
            $auditman = auth()->user()->realname ? auth()->user()->realname : auth()->user()->username;
            //  update 返回受影响的行数
            DB::table('a_sample_info')->whereIn('id', $ids)->increment('check_times', 1, ['status0' => $request->status, 'audit_man' => $auditman]);
            $res1 = DB::table('a_item_data')->whereIn('sample_info_id', $ids)->update(['commit' => $request->status]);

            //初次审核时间
            $date = date('Y-m-d H:i:s');
            DB::table('a_sample_info')->whereIn('id', $ids)->whereNull('check_time')->update(['check_time' => $date]);
            DB::table('a_status_time')->where('contract_id', $contract_id)->whereNull('check_start')->update(['check_start' => $date]);

            // 审核后检查 未审核通过 的记录数
            $res3 = DB::table('a_sample_info')->where('contract_id', $contract_id)->where('status0', ' <> ', '2')->count();
            //如果为0，说明本批次已全部审核通过，此时改变contract的状态
            if($res3 === 0) {
                DB::table('a_contract')->where('id', $contract_id)->update(['status' => '11']);

                //查询此批次是否记录过审核完成的时间
                $check_end = DB::table('a_status_time')->where('contract_id', $contract_id)->value('check_end');
                if(!$check_end) {
                    # 如果没记录过，就记录审核完成的时间
                    $now_time = date("Y/m/d H:i:s"); //当前时间
                    DB::table('a_status_time')->where('contract_id', $contract_id)->update(['check_end' => $now_time]);
                }
            }
            else {
                DB::table('a_contract')->where('id', $contract_id)->update(['status' => '8']);
            }
            DB::commit();
        } catch(\Exception $exception) {
            DB::rollBack();
            return '0';
        }
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //扫描二维码后，查询样品的基础信息
    public function getInfoById(Request $request) {
        //样品详细信息的id
        $id = $request->id;
        if(strlen($id) === 18) {
            $data = DB::table('a_sample_info')->select('self_num', 'guige_xinghao', 'brand', 'manufacturer', 'production_date', 'gqj_ID', 'bar_code_1st')->where('gqj_ID', $id)->orderBy('ctime', 'desc')->first();
        }
        else {
            $data = DB::table('a_sample_info')->select('self_num', 'guige_xinghao', 'brand', 'manufacturer', 'production_date', 'gqj_ID', 'bar_code_1st')->find($id);
        }
        $res = null;

        if($data) {
            # 查到了结果
            $res = response()->json($data);
        }
        else {
            # 未查到结果
            $res = 'false';
        }
        return $res;
    }

    //图片处理
    public function imgdeal($column, $operate, $bar_code) {
        $photo = DB::table('a_sample_info')->where('bar_code', $bar_code)->value($column);
        if(!$photo) {
            return 0;
        }
        $res = DB::table('a_sample_info')->where('bar_code', $bar_code)->update([$column => '']);
        if($res && $operate === 'del') {
            @unlink(substr($photo, 1));
        }
        return $res;
    }

    //驳回记录
    public function rejectLog($iscontract, $id) {
        $data = [];
        $where = $iscontract == 1 ? ['sample_info_id' => null, 'contract_id' => $id] : ['sample_info_id' => $id];
        $data['list'] = DB::table('a_reject_log')->where($where)->select('content', 'ctime', 'manager_realname')->get();
        return view('admin.sampleInfo.rejectLog', compact('data'));
    }
}
